package com.tensquare.user.controller;

import cn.hutool.core.util.StrUtil;
import com.tensquare.user.pojo.Admin;
import com.tensquare.user.service.AdminService;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import jdk.net.SocketFlow;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by WF on 2020/10/24 9:26
 */
@RestController
@RequestMapping("admin")
public class AdminController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private HttpServletRequest request;
    //1.添加管理员
    @PostMapping
    public Result add(@RequestBody Admin admin){
        //1.1)添加 到数据库中
        adminService.add(admin);
        //1.2)返回
        return new Result(StatusCode.OK,true,"添加管理员成功！");
    }

    //2.管理员登录
    @PostMapping("login")
    public Result login(@RequestBody Admin admin){
        //2.1)根据登录名得到登录用户，如果密码一致就登录成功
        Admin loginAdmin = adminService.login(admin);
        //2.2)创建jwt
        String token = jwtUtil.createJWT(loginAdmin.getId(), loginAdmin.getLoginname(), "admin");

        //2.3)返回
        if(loginAdmin != null){
            Map map = new HashMap<>();
            map.put("name",loginAdmin.getLoginname());
            map.put("token",token);
            return new Result(StatusCode.OK,true,"登录成功！",map);
        }
        return new Result(StatusCode.LOGINERROR,false,"登录失败！");
    }

    //3.删除管理员
    @DeleteMapping("{adminId}")
    public Result delete(@PathVariable String adminId){
        //3.1)从请求作用域中得到claims对象
        Claims claims = (Claims) request.getAttribute("claims");
        //3.2)判断是否存在
        if(claims != null){
            //3.3)得到角色
            String roles = (String) claims.get("roles");
            //3.4)判断角色是否存在
            if(StrUtil.isNotBlank(roles) && "admin".equals(roles)){
                adminService.delete(adminId);
                return new Result(StatusCode.OK,true,"删除管理员成功！");
            }
        }
        return new Result(StatusCode.ACCESSERROR,false,"无权删除管理员！");
    }
}
